const { exec, spawn } = require('child_process');
const { promisify } = require('util');
const execPromise = promisify(exec); // 将 exec 转换为 Promise 形式

const fs = require('fs');
const path = require('path');

const _ = require('lodash');
const { log } = require('console');


// console.log(calculateGroundResolution(0.000171661376953125,0));

let tmpdir = 'D:/xiangmu/shujuguanli/tmpdir/'
let inputdirpath = 'D:/xiangmu/shujuguanli/test/'

let tmpjson = {
  "src_file_path":"",
}
let tmpjson1 = {
  "input_file_path":"",
  "max_length":256
}

let polygoncmd = 'D:/xiangmu/shujuguanli/ImageProperties/ImageProperties.exe '
let imgcmd = 'D:/xiangmu/shujuguanli/ImageProperties/Thumbnail.exe '


test()

async function test(params) {

  let resnames = await getAllFile(inputdirpath)
  
  // let cmdstr = 'D:/xiangmu/shujuguanli/ImageProperties/ImageProperties.exe '
  
  resnames.map(item => {
    let cmdstr = polygoncmd
    // let cmdstr = imgcmd

    // let resitem = item.split("\\").pop()

    // console.log(resitem);

    // tmpjson1.input_file_path = '../test/a.tif'
    tmpjson.src_file_path = item

    let tmpjsonrespath = tmpdir + '' + _.random(0, 9999999999) + '.json'
    
    fs.writeFileSync(tmpjsonrespath, JSON.stringify(tmpjson), 'utf8')
  
    cmdstr += tmpjsonrespath

    console.log(cmdstr);
  
    exec(cmdstr, (err, stdout, stderr) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log(stdout);
    });
  })

  // console.log(resnames);



  // const { stdout, stderr } = await execPromise('D:/xiangmu/shujuguanli/ImageProperties/ImageProperties.exe ');
  // console.log(stdout);
}


async function getAllFile(directoryPath) {

  return new Promise((resolve, reject) => {
    fs.readdir(directoryPath, (err, files) => {
      if (err) {
        console.log('Error reading directory:', err);
        return;
      }

      let res_arr = []
    
      files.forEach(file => {
        const filePath = path.join(directoryPath, file);
        // 判断文件是文件还是目录
        let stats = fs.statSync(filePath)
        if (stats.isDirectory()) {
          // console.log(`Directory: ${filePath}`);
        } else {
          // console.log(`File: ${filePath}`);
          res_arr.push(filePath)
        }


      });

      resolve(res_arr)

    });

  })

}

// 导出一个函数，计算地面分辨率
function calculateGroundResolution(degreePerPixel, latitude) {
  // 地球半径（以米为单位）
  const earthRadius = 6371000; // 米
  
  // 地球周长（以米为单位）
  const earthCircumference = 2 * Math.PI * earthRadius;

  // 一度的平均地面长度（赤道上）
  const metersPerDegree = earthCircumference / 360;

  // 纬度的余弦值
  const cosLatitude = Math.cos((latitude * Math.PI) / 180);

  // 地面分辨率（米/像素）
  const groundResolution = degreePerPixel * metersPerDegree * cosLatitude;

  return groundResolution; // 返回米/像素
}


